import dayjs from 'dayjs'

/**
 * 格式化时间
 * @param {Date|string|number} date 
 * @param {string} format 
 * @returns {string}
 */
export function formatTime(date, format = 'YYYY-MM-DD HH:mm:ss') {
  if (!date) return '-'
  return dayjs(date).format(format)
}

/**
 * 格式化持续时间（秒）
 * @param {number} seconds 
 * @returns {string}
 */
export function formatDuration(seconds) {
  if (!seconds) return '-'
  
  if (seconds < 60) {
    return `${seconds}秒`
  } else if (seconds < 3600) {
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return remainingSeconds > 0 ? `${minutes}分${remainingSeconds}秒` : `${minutes}分钟`
  } else {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    return minutes > 0 ? `${hours}小时${minutes}分钟` : `${hours}小时`
  }
}

/**
 * 相对时间
 * @param {Date|string|number} date 
 * @returns {string}
 */
export function relativeTime(date) {
  if (!date) return '-'
  
  const now = dayjs()
  const target = dayjs(date)
  const diff = now.diff(target, 'second')
  
  if (diff < 60) {
    return '刚刚'
  } else if (diff < 3600) {
    return `${Math.floor(diff / 60)}分钟前`
  } else if (diff < 86400) {
    return `${Math.floor(diff / 3600)}小时前`
  } else if (diff < 604800) {
    return `${Math.floor(diff / 86400)}天前`
  } else {
    return target.format('YYYY-MM-DD')
  }
}

/**
 * 判断是否为今天
 * @param {Date|string|number} date 
 * @returns {boolean}
 */
export function isToday(date) {
  if (!date) return false
  return dayjs(date).isSame(dayjs(), 'day')
}

/**
 * 获取时间范围选项
 * @returns {Array}
 */
export function getTimeRangeOptions() {
  const now = dayjs()
  return [
    {
      label: '今天',
      value: [now.startOf('day').toDate(), now.endOf('day').toDate()]
    },
    {
      label: '昨天',
      value: [
        now.subtract(1, 'day').startOf('day').toDate(),
        now.subtract(1, 'day').endOf('day').toDate()
      ]
    },
    {
      label: '最近7天',
      value: [now.subtract(7, 'day').startOf('day').toDate(), now.endOf('day').toDate()]
    },
    {
      label: '最近30天',
      value: [now.subtract(30, 'day').startOf('day').toDate(), now.endOf('day').toDate()]
    },
    {
      label: '本月',
      value: [now.startOf('month').toDate(), now.endOf('month').toDate()]
    },
    {
      label: '上月',
      value: [
        now.subtract(1, 'month').startOf('month').toDate(),
        now.subtract(1, 'month').endOf('month').toDate()
      ]
    }
  ]
} 